#!/bin/bash

# Gitee API 测试脚本
# 用于测试上传文件到 Release 功能

set -e

# 配置
GITEE_TOKEN="4e8d39938cee0a9ea26cf8c5b79c6453"
GITEE_REPO="https://gitee.com/iamzhihuix/claude-code-mirror.git"
TEST_VERSION="test-$(date +%Y%m%d%H%M%S)"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 提取仓库信息
extract_repo_info() {
    local repo_url="$1"
    local path=$(echo "$repo_url" | sed 's|.*gitee\.com/||' | sed 's|\.git||')

    if [[ -z "$path" || "$path" != *"/"* ]]; then
        log_error "无效的 Gitee 仓库地址: $repo_url"
        exit 1
    fi

    echo "$path"
}

# 测试API连接
test_api_connection() {
    local repo_path="$1"

    log_info "测试 API 连接..."

    if response=$(curl -s -H "Authorization: token $GITEE_TOKEN" \
        "https://gitee.com/api/v5/repos/$repo_path" 2>/dev/null); then

        if echo "$response" | jq -e '.id' >/dev/null 2>&1; then
            repo_name=$(echo "$response" | jq -r '.full_name')
            log_info "API 连接成功！仓库: $repo_name"
            return 0
        else
            log_error "API 访问失败"
            echo "$response" | jq -r '.message // "未知错误"' >&2
            return 1
        fi
    else
        log_error "无法连接到 Gitee API"
        return 1
    fi
}

# 创建测试 Release
create_test_release() {
    local repo_path="$1"
    local tag="$2"

    log_info "创建测试 Release: $tag"

    create_url="https://gitee.com/api/v5/repos/$repo_path/releases"

    release_data=$(jq -n \
        --arg tag_name "$tag" \
        --arg name "Test Release $tag" \
        --arg body "这是一个测试 Release，用于验证 API 功能

创建时间: $(date)
测试目的: 验证文件上传功能" \
        --arg target_commitish "main" \
        '{
            "tag_name": $tag_name,
            "name": $name,
            "body": $body,
            "target_commitish": $target_commitish,
            "prerelease": true
        }')

    if response=$(curl -s -X POST \
        -H "Authorization: token $GITEE_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$release_data" \
        "$create_url"); then

        if echo "$response" | jq -e '.id' >/dev/null 2>&1; then
            release_id=$(echo "$response" | jq -r '.id')
            tag_name=$(echo "$response" | jq -r '.tag_name')
            log_info "Release 创建成功！"
            log_info "  ID: $release_id"
            log_info "  Tag: $tag_name"
            echo "$release_id" >&2  # 重定向到stderr避免污染变量
            return 0
        else
            log_error "Release 创建失败"
            log_error "完整响应:"
            echo "$response" >&2
            return 1
        fi
    else
        log_error "API 调用失败"
        return 1
    fi
}

# 上传文件
upload_file() {
    local repo_path="$1"
    local release_id="$2"
    local file_path="$3"

    if [ ! -f "$file_path" ]; then
        log_error "文件不存在: $file_path"
        return 1
    fi

    local filename=$(basename "$file_path")
    local file_size=$(stat -c %s "$file_path" 2>/dev/null || stat -f %z "$file_path" 2>/dev/null || echo "0")

    log_info "上传文件: $filename (${file_size} bytes)"
    log_info "上传 URL: https://gitee.com/api/v5/repos/$repo_path/releases/$release_id/assets"

    # 使用 curl 的 form-data 上传，添加更多调试信息
    log_info "开始上传..."

    if response=$(curl -v -X POST \
        -H "Authorization: token $GITEE_TOKEN" \
        -F "file=@$file_path" \
        "https://gitee.com/api/v5/repos/$repo_path/releases/$release_id/assets" 2>&1); then

        log_info "HTTP 请求完成"

        if echo "$response" | jq -e '.id' >/dev/null 2>&1; then
            download_url=$(echo "$response" | jq -r '.browser_download_url')
            log_info "文件上传成功！"
            log_info "  下载链接: $download_url"
            return 0
        else
            log_error "文件上传失败"
            log_error "上传响应:"
            echo "$response" >&2
            return 1
        fi
    else
        log_error "上传 API 调用失败"
        log_error "curl 输出:"
        echo "$response" >&2
        return 1
    fi
}

# 清理测试 Release
cleanup_test_release() {
    local repo_path="$1"
    local tag="$2"

    log_info "清理测试 Release: $tag"

    # 获取 Release ID
    if release_info=$(curl -s -H "Authorization: token $GITEE_TOKEN" \
        "https://gitee.com/api/v5/repos/$repo_path/releases/tags/$tag" 2>/dev/null); then

        if echo "$release_info" | jq -e '.id' >/dev/null 2>&1; then
            release_id=$(echo "$release_info" | jq -r '.id')

            # 删除 Release
            delete_url="https://gitee.com/api/v5/repos/$repo_path/releases/$release_id"
            if curl -s -X DELETE -H "Authorization: token $GITEE_TOKEN" "$delete_url" >/dev/null 2>&1; then
                log_info "测试 Release 已删除"
            else
                log_warn "删除测试 Release 失败，请手动清理"
            fi
        else
            log_warn "未找到测试 Release"
        fi
    fi
}

# 主函数
main() {
    echo "======================================"
    echo "  Gitee API 测试脚本"
    echo "======================================"
    echo ""

    # 检查依赖
    if ! command -v jq >/dev/null 2>&1; then
        log_error "需要安装 jq 命令"
        exit 1
    fi

    if ! command -v curl >/dev/null 2>&1; then
        log_error "需要安装 curl 命令"
        exit 1
    fi

    # 提取仓库信息
    repo_path=$(extract_repo_info "$GITEE_REPO")
    log_info "仓库路径: $repo_path"

    # 测试 API 连接
    if ! test_api_connection "$repo_path"; then
        log_error "API 连接测试失败，请检查 token 和仓库地址"
        exit 1
    fi

    echo ""

    # 准备测试文件
    test_file="./claude-mirror/stable"
    if [ ! -f "$test_file" ]; then
        log_error "测试文件不存在: $test_file"
        log_info "请先运行 sync-to-gitee.sh 下载文件"
        exit 1
    fi

    # 创建测试 Release
    if create_test_release "$repo_path" "$TEST_VERSION"; then
        # 重新获取release_id，因为函数可能返回了污染的值
        release_info=$(curl -s -H "Authorization: token $GITEE_TOKEN" \
            "https://gitee.com/api/v5/repos/$repo_path/releases/tags/$TEST_VERSION" 2>/dev/null)
        if echo "$release_info" | jq -e '.id' >/dev/null 2>&1; then
            release_id=$(echo "$release_info" | jq -r '.id')
        else
            log_error "无法获取Release ID"
            exit 1
        fi

        log_info "使用 Release ID: $release_id"
        echo ""

        # 上传测试文件
        if upload_file "$repo_path" "$release_id" "$test_file"; then
            echo ""
            log_info "测试成功！文件已上传到 Release"
            log_info "Release 页面: https://gitee.com/$repo_path/releases/tag/$TEST_VERSION"

            # 询问是否清理
            echo ""
            read -p "是否删除测试 Release? (y/N): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                cleanup_test_release "$repo_path" "$TEST_VERSION"
            fi
        else
            log_error "文件上传失败"
            cleanup_test_release "$repo_path" "$TEST_VERSION"
            exit 1
        fi
    else
        log_error "Release 创建失败"
        exit 1
    fi

    echo ""
    log_info "测试完成！"
}

# 运行主函数
main "$@"